import Trie from './trie';
import { EmotionData } from '../../client/components/emotion/data';

let trie = new Trie();

export const emotion_map: any = {}
export const emotion_title_map: any = {}
EmotionData.forEach(item => {
  emotion_map[item.code] = item
  emotion_title_map['[' + item.title + ']'] = item
})

let emotion_list = keys(emotion_map);
trie.build(emotion_list);

/**
 * 转换消息文字
 * @param str 待转换消息文字
 * @param type img/title <img/>/[title]
 */
export const qqWechatEmotionParser = (str: string, type: 'img' | 'title' = 'img') => {
  var indices = trie.search(str);
  indices.reverse().map((idx: any) => {
    let pos = idx[0],
      emotion = emotion_list[idx[1]],
      img = type === 'img' ? '<img src="' + emotion_map[emotion].img + '" alt="' + emotion + '">' : '[' + emotion_map[emotion].title + ']';
    str = splice(str, pos, emotion.length, img);
  });
  return str;
}

export function splice(str: string, index: number, count: number, add: string) {
  return str.slice(0, index) + add + str.slice(index + count);
}

export function keys(map: any) {
  var list = [];
  for (var k in map) {
    if (map.hasOwnProperty(k)) list.push(k);
  }
  return list;
}
